package com.jiujichaoshi.oauth.server.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Description:
 *
 * @author YangLong [410357434@163.com]
 * @version V1.0
 * @date 2021/2/7
 */
@Api(tags = "认证测试")
@RestController
@PreAuthorize("isAuthenticated()")
@RequestMapping("user")
public class AuthenticatedController {
    @Autowired
    private UserDetailsService userDetailsService;

    @ApiOperation("获取当前用户的名字")
    @GetMapping("/name")
    public String getName() {
        /**
         * 如何在用户访问需要认证后的接口获取用户信息
         */
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String account = authentication.getPrincipal().toString();
        //此处替换成账号，邮箱，手机号查询用户信息
        UserDetails user = userDetailsService.loadUserByUsername(account);
        return "Authenticated user password:" + user.getPassword();
    }

    @ApiOperation("需要ROOT角色才能访问")
    @PreAuthorize("hasRole('ROOT')")
    @GetMapping("/role")
    public String getRole() {
        return "Authenticated Role Root";
    }
}
